package jwt

import (
	"fmt"
	"time"

	"github.com/dgrijalva/jwt-go"

	"mychat/internal/common/constants"
	"mychat/internal/common/errors"
)

type tokenClaims struct {
	UserId uint `json:"user_id"`
	jwt.StandardClaims
}

func CreateToken(uid uint, secret string, expiration time.Duration) (string, error) {
	nowTime := time.Now()
	claims := tokenClaims{
		UserId: uid,
		StandardClaims: jwt.StandardClaims{
			IssuedAt:  nowTime.Unix(),
			ExpiresAt: nowTime.Add(expiration).Unix(),
		},
	}
	at := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	token, err := at.SignedString([]byte(secret))
	if err != nil {
		return "", errors.TokenCreateFailed
	}
	return token, nil
}

func ParseToken(tokenStr string, secret string) (*tokenClaims, error) {
	token, err := jwt.ParseWithClaims(tokenStr, &tokenClaims{}, func(token *jwt.Token) (any, error) {
		return []byte(secret), nil
	})
	if err != nil {
		return nil, errors.TokenParseFailed
	}
	if claims, ok := token.Claims.(*tokenClaims); ok && token.Valid {
		if time.Now().Unix() > claims.ExpiresAt {
			return nil, errors.TokenParseFailed
		}
		return claims, nil
	} else {
		return nil, errors.TokenInvalidError
	}
}

func FormatToken(token string) string {
	return fmt.Sprintf("%s_%s", constants.HeaderAuthTokenPrefix, token)
}
